<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\model;



use think\Model;




class AliPay extends  Model
{

    protected $appId = '2021002186655285';//支付宝AppId
    protected $rsaPrivateKey = 'MIIEowIBAAKCAQEAmWdq86gN0XbBSx7ox2IplkNMJcj52gtgyFURcXKEjtfIP6alwphwyJahRdNCmpEVBeMHJKgKxC2cDaEmsB5QzJaqTc/hkexvznZXLJ8Yh1L13zjfN0BAzDlotz/IaEvlbI7E4Ov0wG9kCIuRv7/mGJ/OHoGPEOdhITbPTQJRYIE/4ZZUNWmyCiQ6BTmIiPK3BOzcZTlowfpxWGEGcMVz/zshBFLkVdl25EJYIMXt9kO/Dd4/Cwdl27PkK5BZMIEr/yZBSl1qie4sdSE3hGY8QFomDCCliLqZ4QQocP3s8G9fA29kIZDlaUT/cxYDOZZuE7wJ83/qq3/z1pLDMHWn7QIDAQABAoIBAB+yG4oOjhRaaiPAVi5kHN2cOA6SkPU5Zpzd3sXG+JafBRQJtbQYVS1M2jOYK+nN0j8uIlqzkc3o8pZqVpkLGny7IKMFMcE5zfwlvWtNz/6d6Ilfsdczom/P6M/8EMdj7xpYAVvLxP1BxrRxSgMJflxWIHtzH4FJnWsEbR6nPPMoTPkczlydf4tXqJ+DeddfTZyvtuD+Mcfm+7wKY7kRQVfDRba8tRTFADEtn9AuEczmQOT45DsuUzCw3y8sxz6MxGnSPvVtKlwuX1Tz5Omj5CWzp2CBAvn7H0ltXovb+9mbeBGeNMViHwmLsEgX8WN2VUi66tCeCj6DL04vGEVvk20CgYEA/nG4Os1Df+xpX4/YQwcXqQt1vXtBFCx8r7m44p9XN9VRHqgboQ0VHMFm11DIZN3lZl+lnkpKztA4HQcFgDM/GPOiMwFgeJgSDS6mKYiCC96DCPe1SirV2Y6ov/Ry6H5lZbkWo/6P9/sPJcVzVM5S6c1EzCn+GsQeHzbhKqO+P2cCgYEAmleKUd6m3ShZ2YKOJYWdesHWyoGXVJAu6H015e59JMvP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7SsAZfQIDAQAB';//支付宝公钥
    protected  $charset='utf-8';

    /**
     * 发起退单
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 订单发起时间
     * @return array
     */
    public function TuiPay($totalFee, $outTradeNo,$trade_no, $orderName)
    {
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
            'trade_no'=>$trade_no, //单位 元
            'refund_amount'=>$totalFee, //单位 元
            'subject'=>$orderName, //订单标题
        );

        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.trade.refund',       //接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s',time()),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs);
        return json_decode($result,true);
    }

    /**
     * 发起订单
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 订单发起时间
     * @return array
     */
    public function doPay($totalFee, $outTradeNo, $orderName,$notifyUrl)
    {
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
            'total_amount'=>$totalFee, //单位 元
            'subject'=>$orderName, //订单标题
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.trade.precreate',       //接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $notifyUrl,
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs);
        return json_decode($result,true);
    }

    public function queryPay($outTradeNo)
    {

        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appId,
            'method' => 'alipay.trade.query',       //接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do',$commonConfigs);
        journal(['url' => $outTradeNo, 'data' => $result], 1);
        return json_decode($result,true);
    }
    public function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
    protected function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    /**
     * 校验$value是否非空
     * if not set ,return true;
     *  if is null , return true;
     **/
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


}





